package p.sglmsn.top.ext.wx.controller;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import p.sglmsn.top.ext.wx.entity.InformationReceived;
import p.sglmsn.top.ext.wx.handle.WxMsgHandle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * 控制器接收消息
 *
 * @author 王涛
 * @date 2020/12/11 10:39
 */
@RequestMapping("/receiveInformation")
@RestController
@Slf4j
public class ReceiveNewsController {

    public static final ThreadLocal<JSONObject> THREAD_LOCAL = new InheritableThreadLocal<>();

    @RequestMapping
    public Object 收到消息(HttpServletRequest request, HttpServletResponse response, InformationReceived received) {

        try {
            String read = IoUtil.read(request.getInputStream(), StandardCharsets.UTF_8);
            if (log.isDebugEnabled()) {
                log.debug("消息:{}", read);
            }
            JSONObject jsonObject = JSON.parseObject(read);
            THREAD_LOCAL.set(jsonObject);
            Integer type = jsonObject.getInteger("type");
            if (type == null) {
                return null;
            }

            Optional.ofNullable(WxMsgHandle.get(type)).ifPresent(eventInterface -> eventInterface.handle(jsonObject));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
